# -*- coding: utf-8 -*-
import tornado.httpserver
import tornado.httpclient
import tornado.ioloop
import tornado.web
import MySQLdb,os
import simplejson as json
import sys
import socket
import string
from types import *

"""
HOST="irc.freenode.net"
PORT=6667
NICK="MauBot"
IDENT="maubot"
REALNAME="MauritsBot"
#readbuffer=""
"""
"""
s=socket.socket( )
s.connect((HOST, PORT))
s.send("NICK %s\r\n" % NICK)
s.send("USER %s %s bla :%s\r\n" % (IDENT, HOST, REALNAME))
"""
g_title = ""
g_cloud_info = ""
g_cloud_slogan = ""
g_home = ""
g_forum = ""
g_translate = ""
g_fuckml = ""
g_chat = ""
conn = MySQLdb.connect (host = "localhost", user = "www-data", passwd = "",db = "ncpt")
cursor = conn.cursor ()
cursor.execute("SET NAMES utf8")

def def_title(lang):
	global g_title, g_cloud_info,g_cloud_slogan,g_home,g_forum,g_translate,g_fuckml,g_chat,g_url_home,g_url_forum,g_url_translate,g_url_chat,g_url_fuckml
	g_url_home = "http://211.6.189.194:8888/?lang=" + str(lang)
	g_url_forum = "http://211.6.189.194:8888/forum/board?lang=" + str(lang)
	g_url_translate = "http://211.6.189.194:8888/translate?lang=" + str(lang)
	g_url_chat = "http://211.6.189.194:8888/chat?lang=" + str(lang)
	g_url_fuckml = "http://211.6.189.194:8888/fuckml?lang=" + str(lang)
	if (lang == "en"):
		g_title = "Welcome to Cloudyama"
		g_cloud_info = "Cloudyama.com"
		g_cloud_slogan = "International Students @ Japan "
		g_home = "home"
		g_forum = "forums"
		g_translate = "human translation"
		g_fuckml = "fuck my life"
		g_chat = "chat"

	if (lang == "jp"):
		g_title = "雲山へようこそ"
		g_cloud_info = "Cloudyama.com"
		g_cloud_slogan = "日本の国際学生"
		g_home = "ホーム"
		g_forum = "掲示板"
		g_translate = "人力翻訳"
		g_fuckml = "この野郎"
		g_chat = "チャット"
		
	if (lang == "cn"):
		g_title = "欢迎来到云山"
		g_cloud_info = "Cloudyama.com"
		g_cloud_slogan = "在日本的国际学生"
		g_home = "首页"
		g_forum = "论坛"
		g_translate = "人肉翻译"
		g_fuckml = "我靠！"
		g_chat = "聊天"
		
class MainHandler(tornado.web.RequestHandler):
    def get(self):
		req_lang = str(self.get_argument('lang'))
	#Oh yes, this is where you start all the Google Applications Engine shit !!! Yeah !
		title = ""
		languages = "<a href = '/?lang=jp'>日本語</a><a href = '/?lang=en'>English</a>"
		script = "js/hp-"+ str(req_lang) + ".js"
		cursor.execute ("""
				SELECT title, time, body, id
				FROM cloud_titan
				WHERE lang = %s
				ORDER BY time DESC
				LIMIT 20
				""",req_lang)
		rows = cursor.fetchall()
		def_title(str(req_lang))
		if (req_lang == 'en'):
			like = "Like"
			dislike = "Dislike"
			speak = "Say Something"
			ladder = "Ladder"
			facebook = "Find us on Facebook"
			twitter = "Follow us on Twitter"
			translation = "Someone translate this shit for me!"
			self_intro = "Why am I here ?!"
			fml = "Fuck my life in Japan"
			reply_text = " reply "
		elif (req_lang == 'jp'):
			like = "好き"
			dislike = "違う"
			speak = "つぶやく"
			ladder = "ランキング"
			facebook = "フェスブックで見つける"
			twitter = "ツイターでフォーロする"
			translation = "通訳なんかできるか！ボケ!"
			self_intro = "自己紹介します"
			fml = "この野郎!!!!!!!!!!!"
			reply_text = " コメントする "
		elif (req_lang == 'cn'):
			title = "歡迎來到雲山"
			cloud_info = "Cloudyama.com"
			cloud_slogan = "在日本的國際學生"
			home = "首頁"
			like = "頂"
			dislike = "踩"
			speak = "隨邊說說"
			ladder = "排行"
		blogs = []
		for row in rows:
			blogs.append( str(row[0]) + "<em>{</em><li>" + str(row[2]) + 
				"</li>" + "<li>" + str(row[1]) + "</li><p style = 'border-bottom:#333 1px dotted;'><em>}</em>" + 
				"<a href = 'http://211.6.189.194:8888/titan/contents?id=" + str(row[3])
				+ "'>" + reply_text + "</a><em>{</em></p>")
		self.render("cloud/hp-en.html", 
			title = g_title,
			blogs = blogs,
			cloud_info = g_cloud_info,
			cloud_slogan = g_cloud_slogan,
			languages = languages,
			script = script,
			#urls - Start
			home = g_home,
			url_home = g_url_home,
			forum = g_forum,
			url_forum = g_url_forum,
			translate = g_translate,
			url_translate = g_url_translate,
			fuckml = g_fuckml,
			url_fuckml = g_url_fuckml,
			chat = g_chat,
			url_chat = g_url_chat,
			#urls - End
			like = like,
			dislike = dislike,
			speak = speak,
			ladder = ladder, 
			facebook = facebook,
			twitter = twitter,
			translation = translation,
			self_intro = self_intro,
			fml = fml )

class ChatHandler(tornado.web.RequestHandler):
    @tornado.web.asynchronous
    def get(self):
    	s=socket.socket( )
	s.connect((HOST, PORT))
	s.send("NICK %s\r\n" % NICK)
	s.send("USER %s %s bla :%s\r\n" % (IDENT, HOST, REALNAME))	
	while 1:	
		readbuffer = ""	
		readbuffer=readbuffer+s.recv(1024)
    		temp=string.split(readbuffer, "\n")	
		readbuffer=temp.pop()	
		self.write(str(temp))	
		for line in temp:
        		line=string.rstrip(line)
        		line=string.split(line)
        		if(line[0]=="PING"):	
				s.send("PONG %s\r\n" % line[1])        
		self.finish()
class AdminBlogHandler(tornado.web.RequestHandler):
	def get(self,req_id):
		if req_id == "board":
			def_title('cn')
			forum_title_text = "最新日志"
			forum_time_text = "最后更新"
			id = ""
			titan = "回去论坛/掲示板に戻る/Go back to forum"
			languages = "<a href = '#'>道可道非常道</a>"
			script = "js/forum-cn.js"
			cursor.execute ("""
					SELECT title, time, id 
					FROM cloud_titan
					ORDER BY time DESC
					LIMIT 20
					""")
			rows = cursor.fetchall()
			topics = []
			file = "cloud/titan.html"
			for row in rows:
				topics.append("<a href = '/titan/contents?id="+ str(row[2]) + "'>"+ str(row[0]) + "</a>" + "<li>" + str(row[1]) + "</li>")
		if req_id == "contents":
			file = "cloud/titan-contents.html"
			req_id = str(self.get_argument('id'))
			forum_title_text = ""
			forum_time_text = "Last updated"
			titan = "Home／ホーム"
			languages = "<a href = '/forum/contents?lang=jp&id=" + req_id + "'>日本語</a><a href = '/forum/contents?lang=en&id="+ req_id + "'>English</a>"
			script = "js/contents-cn.js"
			cursor.execute ("""
					SELECT body, time
					FROM cloud_titan
					WHERE id = %s
					""",req_id)
			piece = cursor.fetchone()
			cursor.execute ("""
					SELECT body, time 
					FROM cloud_titan_replies
					WHERE topic_id = %s
					ORDER BY time DESC
					""",req_id)
			rows = cursor.fetchall()
			topics = []
			id = req_id
			topics.append("<a>" + str(piece[0]) + "<em>" + str(piece[1]) + "</em>""</a>")
			for row in rows:
				topics.append("<a>"+ str(row[0]) + "<em>" + str(row[1]) + "</em>""</a>")
		self.render(file,
			#Local Items
			id = id,
			forum_time_text = forum_time_text,
			forum_title_text = forum_title_text,
			topics = topics,
			url_forum = "/?lang=en",
			titan = titan,
			#Under are all commons
			title = g_title,
			cloud_info = g_cloud_info,
			cloud_slogan = g_cloud_slogan,
			home = g_home,
			forum = g_forum,
			translate =  g_translate,
			fuckml = g_fuckml,
			chat = g_chat,
			script = script,
			languages = languages)

class ForumHandler(tornado.web.RequestHandler):
	def get(self,req):
		if req == "board":
			req_lang = str(self.get_argument('lang'))
			def_title(req_lang)
			if req_lang == "en":
				forum_title_text = "All Topics:"
				forum_time_text = "Last updated"
				titan = "titan's blog"
			elif req_lang == "jp":
				forum_title_text = "スレッド："
				forum_time_text = "最新更新"
				titan = "サイトブログ"
			languages = "<a href = '/forum/board?lang=jp'>日本語</a><a href = '/forum/board?lang=en'>English</a>"
			script = "js/forum-"+ str(req_lang) + ".js"
			cursor.execute ("""
					SELECT title, time, id
					FROM cloud_forum
					WHERE lang = %s
					ORDER BY time DESC
					LIMIT 20
					""",req_lang)
			rows = cursor.fetchall()
			topics = []
			id = ""
			file = "cloud/forum.html"
			for row in rows:
				topics.append("<a href = '/forum/contents?id="+ str(row[2]) + "&lang=" + req_lang + "'>"+ str(row[0]) + "</a>" + "<li>" + str(row[1]) + "</li>")
		elif req == "contents":
			file = "cloud/content.html"
			req_id = str(self.get_argument('id'))
			req_lang = str(self.get_argument('lang'))
			def_title(req_lang)
			if req_lang == "en":
				forum_title_text = ""
				forum_time_text = "Last updated"
				titan = "Go back to forum"
			elif req_lang == "jp":
				forum_title_text = ""
				forum_time_text = "最新更新"
				titan = "掲示板に戻る"
			languages = "<a href = '/forum/contents?lang=jp&id=" + req_id + "'>日本語</a><a href = '/forum/contents?lang=en&id="+ req_id + "'>English</a>"
			script = "js/contents-"+ str(req_lang) + ".js"
			cursor.execute ("""
					SELECT body, time
					FROM cloud_forum
					WHERE id = %s
					""",req_id)
			piece = cursor.fetchone()
			cursor.execute ("""
					SELECT body, time FROM cloud_replies
					WHERE topic_id = %s
					ORDER BY time ASC
					""",req_id)
			rows = cursor.fetchall()
			topics = []
			id = req_id
			topics.append("<a>" + str(piece[0]) + "<em>" + str(piece[1]) + "</em>""</a>")
			for row in rows:
				topics.append("<a>"+ str(row[0]) + "<em>" + str(row[1]) + "</em>""</a>")
		
		self.render(file,
			#Local Items
			forum_time_text = forum_time_text,
			forum_title_text = forum_title_text,
			topics = topics,
			titan = titan,
			id = id,
			#Under are all commons
			title = g_title,
			cloud_info = g_cloud_info,
			cloud_slogan = g_cloud_slogan,
			home = g_home,
			forum = g_forum,
			translate =  g_translate,
			fuckml = g_fuckml,
			chat = g_chat,
			script = script,
			languages = languages,
			url_home = g_url_home,
			url_forum = g_url_forum,
			url_translate = g_url_translate,
			url_chat = g_url_chat,
			url_fuckml = g_url_fuckml)

class InfoHandler(tornado.web.RequestHandler):
	def post(self, data):
		if data == "":
			lang = self.get_argument("lang").encode("utf-8","ignore")
			title = self.get_argument("title").encode("utf-8","ignore")
			body = self.get_argument("body").encode("utf-8","ignore")
			cursor.execute("""
						SELECT id FROM cloud_forum
						ORDER BY id DESC
						LIMIT 1""")
			row = cursor.fetchone()
			last_forum_id = int(row[0]) + 1
			cursor.execute("""INSERT INTO cloud_forum
						VALUES (%s, %s, %s, %s,CURRENT_TIMESTAMP)
						""", (title, body,last_forum_id,lang,))
			output = "Post Success!"
		elif data == "titan":
			title = self.get_argument("title").encode("utf-8","ignore")
			lang = title[5:7]
			body = self.get_argument("body").encode("utf-8","ignore")
			if (body[:17] <> "password:ododlaed") or (title[:4] <> "lang"):
				output = "休想发布任何消息！STAY WHILE YOU ENJOY YOUR LAST MOMENTS!!"
			else:
				cursor.execute("""
						SELECT id FROM cloud_titan
						ORDER BY id DESC
						LIMIT 1""")
				row = cursor.fetchone()
				last_titan_id = int(row[0]) + 1
				cursor.execute("""INSERT INTO cloud_titan
							VALUES (%s, %s, %s, %s,CURRENT_TIMESTAMP)
							""", (title[7:], body[17:],last_titan_id,lang,))
				output = "我果然是天才！居然不知道你是谁！"
		elif data == "reply":
			body = self.get_argument("body").encode("utf-8","ignore")
			id = self.get_argument("id").encode("utf-8","ignore")
			cursor.execute("""
						SELECT id FROM cloud_replies
						WHERE topic_id = %s
						ORDER BY id DESC
						LIMIT 1""",(id))
			row = cursor.fetchone()
			try:
				last_titan_id = int(row[0]) + 1
			except Exception:
				last_titan_id = 1
			cursor.execute("""INSERT INTO cloud_replies
						VALUES (%s, %s,CURRENT_TIMESTAMP, %s)
						""", (id, body,last_titan_id))
			cursor.execute("""
							UPDATE cloud_forum
							SET time = CURRENT_TIMESTAMP
							WHERE id = %s
							""",id)
			output = "Post Success!"
		elif data == "replytitan":
			body = self.get_argument("body").encode("utf-8","ignore")
			id = self.get_argument("id").encode("utf-8","ignore")
			cursor.execute("""
						SELECT id FROM cloud_titan_replies
						WHERE topic_id = %s
						ORDER BY id DESC
						LIMIT 1""",(id))
			row = cursor.fetchone()
			try:
				last_titan_id = int(row[0]) + 1
			except Exception:
				last_titan_id = 1
			cursor.execute("""INSERT INTO cloud_titan_replies
						VALUES (%s, %s,CURRENT_TIMESTAMP, %s)
						""", (id, body,last_titan_id))
			cursor.execute("""
							UPDATE cloud_titan
							SET time = CURRENT_TIMESTAMP
							WHERE id = %s
							""",id)
			output = "Post Success!"
			
			
		self.write(output)
	def get(self, req_id):
		if ( req_id == "info.json"):
			info_since = int(self.get_argument('since'))	
			info_lang = str(self.get_argument('lang'))
			cursor.execute("""
					SELECT iid FROM cloud_info
					WHERE info_lang = %s
					ORDER BY iid DESC
					LIMIT 1	
					""",info_lang)
			row = cursor.fetchone()
			last_id = row[0]
			if ( int(info_since) <= 0 ):
				cursor.execute("""
						SELECT author, title, iid, time, rank
						FROM cloud_info
						WHERE info_lang = %s
						ORDER by time DESC
						LIMIT 30	
						""",info_lang)
				rows = cursor.fetchall()
				new_tweet = len(rows)	
				output = []
				output.append({'info_diff':0,
						'new_tweet':new_tweet})	
				for row in rows:
					output.append({'author':row[0],
							'title':row[1],
							'id':row[2],
							'time':str(row[3])[-8:],
							'rank':row[4]})		
			else:	
				id_diff = last_id - int(info_since)	
				if ( id_diff > 0 ):
					cursor.execute("""
							SELECT author, title, iid, time, rank
							FROM cloud_info
							WHERE iid  > %s
							AND info_lang = %s
							ORDER BY time DESC	
							""",(info_since,info_lang))		
					rows = cursor.fetchall()	
					new_tweet = len(rows)	
					output = []
					output.append({'info_diff':id_diff,
							'new_tweet':new_tweet})	
					for row in rows:		
						output.append({'author':row[0],
								'title':row[1],
								'id':row[2],
								'time':str(row[3]),
								'rank':row[4]})       
        			else:
					output = []	
					output.append({'info_diff' : 0})
		elif ( req_id == 'ranking.json' ):
			rank_lang = str(self.get_argument('lang'))
			cursor.execute("""
					SELECT author, title, iid, time, rank
					FROM cloud_info
					WHERE info_lang = %s	
					ORDER BY rank DESC
					LIMIT 10	
					""",rank_lang)
			rows = cursor.fetchall()
			output = []
			for row in rows:
				output.append({'author':row[0],
						'title':row[1],
						'id':row[2],
						'time':str(row[3]),
						'rank':row[4]})	
		else:
			output = 0	
		self.write(json.dumps(output, indent=4 ))

settings = {
    "static_path": os.path.join(os.path.dirname(__file__), "cloud")
}
	
application = tornado.web.Application([
	(r"/", MainHandler),
	(r"/json/(.*)", InfoHandler),
	(r"/chat",ChatHandler),
	(r"/forum/(.*)",ForumHandler),
	(r"/titan/(.*)",AdminBlogHandler),
	],**settings)

if __name__ == "__main__":
    http_server = tornado.httpserver.HTTPServer(application)
    http_server.listen(8888)
    tornado.ioloop.IOLoop.instance().start()
